// 引入数据管理工具
const db = require('../../utils/db.js');
const { formatTime } = require('../../utils/format.js');
const mockData = require('../../utils/mockData.js');

Page({
  data: {
    confessionList: [],
    loading: true,
    page: 1,
    pageSize: 10,
    hasMore: true,
    marqueeTexts: [],   // 跑马灯文字数组
    marqueeIndex: 0     // 当前显示的跑马灯索引
  },

  onLoad() {
    this.generateMarqueeTexts();
    this.startMarquee();
    this.getConfessionList();
  },

  // 生成跑马灯文字
  generateMarqueeTexts() {
    const texts = [];
    for (let i = 0; i < 15; i++) {
      const nickname = mockData.generateRandomNickname();
      const contact = mockData.generateRandomContact('wechat');
      const targetName = mockData.generateRandomNickname();
      const content = mockData.generateRandomContent().substring(0, 20) + '...';
      
      // 随机生成不同类型的提示文字
      const type = Math.floor(Math.random() * 6);
      let text = '';
      
      switch(type) {
        case 0:
          text = `${nickname} 给 ${targetName} 表白了，快来围观~`;
          break;
        case 1:
          text = `${nickname} 留下了联系方式「${contact}」，期待有缘人~`;
          break;
        case 2:
          text = `${nickname} 偷偷关注了 ${targetName} 很久，今天终于鼓起勇气表白啦！`;
          break;
        case 3:
          text = `有人在校园表白墙匿名表白 ${targetName}，猜猜是谁呢？`;
          break;
        case 4:
          text = `刚刚有人表白说："${content}" 真是太甜了！`;
          break;
        case 5:
          text = `【最新表白】${nickname} 对 ${targetName} 说了一些悄悄话...`;
          break;
      }
      
      texts.push(text);
    }
    
    this.setData({
      marqueeTexts: texts
    });
  },

  // 开始跑马灯
  startMarquee() {
    // 每3秒切换一条文字，添加淡入淡出效果
    this.marqueeTimer = setInterval(() => {
      this.setData({
        marqueeTexts: this.data.marqueeTexts,
        marqueeIndex: (this.data.marqueeIndex + 1) % this.data.marqueeTexts.length
      });
    }, 3000);
  },

  // 获取表白列表
  async getConfessionList() {
    try {
      let list = await db.getConfessionList(this.data.page, this.data.pageSize);
      
      // 如果没有数据，则使用模拟数据
      if (list.length === 0) {
        list = mockData.generateConfessions(20);
        // 将模拟数据保存到本地存储
        wx.setStorageSync('confessions', list);
      }
      
      // 格式化时间
      const formattedList = list.map(item => ({
        ...item,
        time: formatTime(item.createTime),
        isLiked: false // 默认未点赞
      }));
      
      this.setData({
        confessionList: formattedList,
        loading: false,
        hasMore: list.length === this.data.pageSize
      });
    } catch (error) {
      console.error('获取表白列表失败:', error);
      
      // 使用模拟数据作为后备
      const mockList = mockData.generateConfessions(20);
      const formattedList = mockList.map(item => ({
        ...item,
        time: formatTime(item.createTime),
        isLiked: false
      }));
      
      this.setData({
        confessionList: formattedList,
        loading: false
      });
      
      wx.showToast({
        title: '已显示模拟数据',
        icon: 'none'
      });
    }
  },

  // 跳转到详情页
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 点赞功能
  async handleLike(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.confessionList;
    const isLiked = !list[index].isLiked;
    
    try {
      // 更新数据库中的点赞数
      await db.likeConfession(list[index].id, isLiked);
      
      // 更新本地状态
      list[index].isLiked = isLiked;
      list[index].likes += isLiked ? 1 : -1;
      
      this.setData({
        confessionList: list
      });
    } catch (error) {
      console.error('点赞操作失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1
    }, () => {
      this.getConfessionList();
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      page: this.data.page + 1
    }, () => {
      this.loadMore();
    });
  },

  // 加载更多数据
  async loadMore() {
    try {
      let list = await db.getConfessionList(this.data.page, this.data.pageSize);
      
      // 如果没有数据，则使用模拟数据
      if (list.length === 0) {
        list = mockData.generateConfessions(10);
      }
      
      if (list.length === 0) {
        this.setData({
          hasMore: false
        });
        return;
      }
      
      // 格式化时间
      const formattedList = list.map(item => ({
        ...item,
        time: formatTime(item.createTime),
        isLiked: false // 默认未点赞
      }));
      
      this.setData({
        confessionList: [...this.data.confessionList, ...formattedList],
        hasMore: list.length === this.data.pageSize
      });
    } catch (error) {
      console.error('加载更多数据失败:', error);
      
      // 使用模拟数据
      const mockList = mockData.generateConfessions(10);
      const formattedList = mockList.map(item => ({
        ...item,
        time: formatTime(item.createTime),
        isLiked: false
      }));
      
      this.setData({
        confessionList: [...this.data.confessionList, ...formattedList],
      });
      
      wx.showToast({
        title: '已显示更多模拟数据',
        icon: 'none'
      });
    }
  },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.marqueeTimer) {
      clearInterval(this.marqueeTimer);
    }
  }
})